from datetime import date, timedelta
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from userapp.models import Users
from payment.models import OrderInfo


class UserToalAPIView(APIView):
    permission_classes = [IsAdminUser]  # 权限校验

    def get(self, request):
        # 获取用户总数
        count = Users.objects.count()
        return Response({'count': count})


class UserDayCountView(APIView):
    '''获取日曾用户数'''
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取用户表中 日增用户 今天
        now_date = date.today()
        year = now_date.year
        month = now_date.month
        day = now_date.day

        count = Users.objects.filter(date_joined__year=year, date_joined__month=month, date_joined__day=day).count()

        return Response({'count': count})


class UserActiveCountView(APIView):
    '''获取日活跃用户总数'''
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取last_login
        now_date = date.today()
        year = now_date.year
        month = now_date.month
        day = now_date.day

        count = Users.objects.filter(last_login__year=year, last_login__month=month, last_login__day=day).count()
        return Response({'count': count})


class TimeOrderCountView(APIView):
    '''获取今日和昨日下单量'''
    permission_classes = [IsAdminUser]

    def get(self, request):
        t_count_list = []  # 今日下单量
        y_count_list = []  # 昨日下单量
        today = date.today()
        yesterday = today + timedelta(days=-1)
        times = ['00', '02', '04', '06', '08', '10', '12', '14', '16', '18', '20', '22']  # 一些时间点 06开头：……
        for t in times:
            t_count = OrderInfo.objects.filter(create_time__year=today.year, create_time__month = today.month, create_time__day = today.day, create_time__hour__lte= t).count()
            t_count_list.append(t_count)
            y_count = OrderInfo.objects.filter(create_time__year=yesterday.year, create_time__month = yesterday.month, create_time__day = yesterday.day, create_time__hour__lte = t).count()
            y_count_list.append(y_count)

        t_count_list = ['100','700','12','232','32','1000','329','45','99','321','500','89']
        y_count_list = ['1','32','90','221','654','89','120','0','49','921','500','49']
        return Response({'t_count_list': t_count_list, 'y_count_list': y_count_list})
